package com.kara.webapp.components.student;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.kara.entity.Clazz;
import com.kara.entity.Student;
import com.kara.service.ClazzManager;
import com.kara.service.StudentManager;
import com.kara.webapp.pages.admin.student.StudentAdmin;

public class StudentForm {

  @Parameter(required = true)
  @Property
  private long clazzId;

  @Parameter
  @Property
  private long studentId;

  @Property
  @Persist
  private Student student;

  @Inject
  private ClazzManager clazzManager;

  @Inject
  private StudentManager studentManager;


  @InjectPage
  private StudentAdmin studentAdmin;

  @Component(id = "firstName", parameters = { "value=student.firstName", "validate=required" })
  private TextField firstName;

  @Component(id = "lastName", parameters = { "value=student.lastName", "validate=required" })
  private TextField lastName;

  @Component(id = "mobilePhone", parameters = { "value=student.mobilePhone", "validate=required,regexp","size=8" })
  private TextField mobilePhone;

  @Component(id = "email", parameters = { "value=student.email", "validate=required,email" })
  private TextField email;

  @Parameter(value = "message:button.save", defaultPrefix = BindingConstants.LITERAL)
  @Property
  private String submitLabel;

  private Clazz clazz;

  @SetupRender
  private void setUp() {
    if (studentId == 0) {
      student = new Student();
    }
    else {
      student = studentManager.getStudent(studentId);
    }
  }

  @OnEvent(component = "form", value = EventConstants.SUCCESS)
  private Object success() {

    clazz = clazzManager.getClazz(clazzId);
    Student saveStudent = studentManager.addStudentToClazz(clazz, student);

    return studentAdmin;
  }

  Object onCancel() {
    studentAdmin.setMyClazzId(clazzId);
    return studentAdmin;
  }

}
